package com.wzh.himalaya;


import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.wzh.himalaya.adapters.PlayerTrackPagerAdapter;
import com.wzh.himalaya.base.BaseActivity;
import com.wzh.himalaya.interfaces.IPlayerCallBack;
import com.wzh.himalaya.presenters.PlayerPresenter;
import com.wzh.himalaya.views.PopWindow;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * className:BaseActivity
 * Author:WZH
 * Time:2022-04-09
 */
public class PlayerActivity extends BaseActivity implements IPlayerCallBack, ViewPager.OnPageChangeListener {

    private static final String TAG = "PlayerActivity";
    private ImageView mControlBtn;
    private PlayerPresenter mPlayerPresenter;
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");
    private TextView mTotalDuration;
    private TextView mCurrentPosition;
    private SeekBar mDurationBar;
    private int mCurrentProgress = 0;
    private boolean mIsUserTouchProgressBar = false;
    private ImageView mPlayNextBtn;
    private ImageView mPlayPreBtn;
    private TextView mTrackTitleTv;
    private String mTrackTitleText;
    private ViewPager mTrackPageView;
    private PlayerTrackPagerAdapter mTrackPagerAdapter;
    private boolean mIsUserSlidePager = false;
    private ImageView mPlayModeSwitch;


    private XmPlayListControl.PlayMode mCurrentMode = PLAY_MODEL_LIST;
    //
    private static Map<XmPlayListControl.PlayMode, XmPlayListControl.PlayMode> sPlayModeRule = new HashMap<>();
    static{
        sPlayModeRule.put(PLAY_MODEL_LIST,PLAY_MODEL_LIST_LOOP);
        sPlayModeRule.put(PLAY_MODEL_LIST_LOOP,PLAY_MODEL_RANDOM);
        sPlayModeRule.put(PLAY_MODEL_RANDOM,PLAY_MODEL_SINGLE_LOOP);
        sPlayModeRule.put(PLAY_MODEL_SINGLE_LOOP,PLAY_MODEL_LIST);
    }

    private View mPlayListBtn;
    private PopWindow mPopWindow;
    private ValueAnimator mEnterBgAnimator;
    private ValueAnimator mOutBgAnimator;

    //处理播放模式的切换
    //1、默认的是：PLAY_MODEL_LIST
    //2、点击的时候切换到列表循环 PLAY_MODEL_LIST_LOOP
    //3、随机播放 PLAY_MODEL_RANDOM
    //4、单曲循环 PLAY_MODEL_SINGLE_LOOP


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        initView();
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallback(this);
        //在界面初始化之后才获取数据
        mPlayerPresenter.getPlayList();
        initEvent();
        initBgAnimation();
        //startPlay();  如果在这里就加载play 可能会出现 播放器还没有加载完毕 就去调用播放音频 出现播放失败的错误

    }

    private void initBgAnimation() {
        mEnterBgAnimator = ValueAnimator.ofFloat(1.0f,0.5f);
        mEnterBgAnimator.setDuration(300);
        mEnterBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                //处理下背景，将背景变暗
                float value = (float)animation.getAnimatedValue();
                updateBgAlpha(value);
            }
        });

        mOutBgAnimator = ValueAnimator.ofFloat(0.5f,1.0f);
        mOutBgAnimator.setDuration(300);
        mOutBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float)animation.getAnimatedValue();
                updateBgAlpha(value);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放资源
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unregisterViewCallback(this);
            mPlayerPresenter=null;
        }
    }

    /**
     * 开始播放       //不在这里调用play（）  防止出现播放器还没准备好就调用播放音频
     */
//    private void startPlay() {
//
//        if (mPlayerPresenter != null) {
//            mPlayerPresenter.play();
//        }
//    }





    /**
     * 给控件设置相关的事件
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        mControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放-->暂停  非播放-->播放
                if (mPlayerPresenter.isPlay()) {
                    mPlayerPresenter.pause();
                }else{
                    mPlayerPresenter.play();
                }
            }
        });

        mDurationBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean isFromUser) {
                if (isFromUser) {
                    mCurrentProgress=progress;
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar =true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar=false;
                //手离开进度条的时候更新
                mPlayerPresenter.seekTo(mCurrentProgress);
            }
        });

        mPlayNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放下一个节目
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playNext();
                }


            }
        });

        //设置一个滑动监听
        mTrackPageView.addOnPageChangeListener(this);

        mTrackPageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch(action){
                    case MotionEvent.ACTION_DOWN:
                        mIsUserSlidePager=true;
                        break;


                }
                return false;
            }
        });


        mPlayPreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放前一个节目
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playPre();
                }
            }
        });


    mPlayModeSwitch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SwitchPlayMode();

        }
    });

    mPlayListBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //完成播放列表的展示。
            mPopWindow.showAtLocation(v,Gravity.BOTTOM,0,0);
            //修改透明度有一个时间
            mEnterBgAnimator.start();

        }
    });
    //这个是点击消失
    mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            mOutBgAnimator.start();
        }
    });


    mPopWindow.setPlayItemClickListener(new PopWindow.playListItemClickListener() {
        @Override
        public void onItemClick(int position) {
            //播放里的列表被点击了
            if (mPlayerPresenter != null) {
                mPlayerPresenter.playByIndex(position);
            }
        }
    });

    mPopWindow.setPlayListActionClickListener(new PopWindow.PlayListActionClickListener() {
        @Override
        public void onPlayModeClick() {
            SwitchPlayMode();
        }

        @Override
        public void onOrderClick() {
            //点击了切换正序和逆序
            if (mPlayerPresenter != null) {
                mPlayerPresenter.reversePlayList();
            }

        }
    });



    }


    private void SwitchPlayMode() {
        //处理播放模式的切换
        //根据当前的mode获取到下一个mode
        XmPlayListControl.PlayMode playMode = sPlayModeRule.get(mCurrentMode);
        //修改播放模式
        if (mPlayerPresenter != null) {
            mPlayerPresenter.switchPlayMode(playMode);
        }
    }

    //修改alpha值
    public void updateBgAlpha(float alpha){
        Window window  = getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.alpha = alpha;
        window.setAttributes(attributes);
    }

    //1、默认的是：PLAY_MODEL_LIST
    //2、点击的时候切换到列表循环 PLAY_MODEL_LIST_LOOP
    //3、随机播放 PLAY_MODEL_RANDOM
    //4、单曲循环 PLAY_MODEL_SINGLE_LOOP
    private void updatePlayModeBtnImg() {
        int resId = R.mipmap.sort_descending;
        switch (mCurrentMode){
            case PLAY_MODEL_LIST:
                resId = R.mipmap.sort_descending;
                break;
            case PLAY_MODEL_LIST_LOOP:
                resId = R.mipmap.play_mode_loop_normal;
                break;
            case PLAY_MODEL_RANDOM:
                resId = R.mipmap.play_mode_random_normal;
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                resId = R.mipmap.play_mode_loop_one_normal;
                break;
        }
        mPlayModeSwitch.setImageResource(resId);
    }

    /**
     * 找到各个控件
     */
    private void initView() {
        mControlBtn = this.findViewById(R.id.play_or_stop);
        mTotalDuration = this.findViewById(R.id.track_duration);
        mCurrentPosition = this.findViewById(R.id.current_position);
        mDurationBar = this.findViewById(R.id.track_seek_bar);
        mPlayNextBtn = this.findViewById(R.id.player_next);
        mPlayPreBtn = this.findViewById(R.id.player_pre);

        mTrackTitleTv = this.findViewById(R.id.track_title);
        if (!TextUtils.isEmpty(mTrackTitleText)) {
            mTrackTitleTv.setText(mTrackTitleText);
        }

        mTrackPageView = this.findViewById(R.id.track_pager_view);
        //创建适配器
        mTrackPagerAdapter = new PlayerTrackPagerAdapter();
        //设置适配器
        mTrackPageView.setAdapter(mTrackPagerAdapter);
        //切换播放模式的按钮
        mPlayModeSwitch = this.findViewById(R.id.player_mode_switch_btn);

        //播放列表
        mPlayListBtn = this.findViewById(R.id.player_list);
        mPopWindow = new PopWindow();

    }




    @Override
    public void onPlayStart() {
        //开始播放，修改UI成暂停的按钮
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.stop_music);
        }

    }

    @Override
    public void onPlayPause() {
        //暂停播放，修改UI成播放的按钮
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.player);
        }

    }

    @Override
    public void onPlayStop() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.player);
        }
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void nextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {
        //把数据设置到适配器里
        if (mTrackPagerAdapter != null) {

            mTrackPagerAdapter.setData(list);
        }

        //数据回来之后 也要给播放列表
        if (mPopWindow != null) {
            mPopWindow.setListData(list);
        }

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {
        //UI回调的显示
        mCurrentMode = playMode;
        //更新pop里的播放模式
        mPopWindow.updatePlayMode(mCurrentMode);
        updatePlayModeBtnImg();
    }

    @Override
    public void onProgressChange(int currentDuration, int total) {

        mDurationBar.setMax(total);


        //更新播放进度，更新进度条
        String totalDuration;
        String currentPosition;
        if (total>1000*60*60) {
            totalDuration =  mHourFormat.format(total);
            currentPosition = mHourFormat.format(currentDuration);
        }else{
            totalDuration  = mMinFormat.format(total);
            currentPosition = mMinFormat.format(currentDuration);
        }
        if (mTotalDuration != null) {
            mTotalDuration.setText(totalDuration);
        }
        //更新当前时间
        if (mCurrentPosition != null) {
            mCurrentPosition.setText(currentPosition);
        }

        //更新进度
        if (!mIsUserTouchProgressBar) {
            mDurationBar.setProgress(currentDuration);
        }



    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdLoaded() {

    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {
        this.mTrackTitleText =track.getTrackTitle() ;

        if (mTrackTitleTv != null) {
            //设置当前节目的标题
            mTrackTitleTv.setText(mTrackTitleText);
        }
        //当节目改变的时候，我们就获取当前的播放器中的位置
        //当前的节目改变后，要修改页面的图片
        if (mTrackPageView != null) {
            mTrackPageView.setCurrentItem(playIndex,true);
        }

        if (mPopWindow != null) {
            mPopWindow.setCurrentPlayPosition(playIndex);
        }




    }

    @Override
    public void updateListOrder(boolean isReverse) {
        mPopWindow.updateOrderIcon(isReverse);

    }


    //------------------------------滑动监听的三个方法----------------

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        //当页面选中的时候，就去切换播放的内容
        if (mPlayerPresenter != null&&mIsUserSlidePager) {
            mPlayerPresenter.playByIndex(position);
        }
        mIsUserSlidePager=false;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    //--------------------------------------------------------------
}
